package com.jokerx.ohos.fasttrpg.data.preferences;

import com.jokerx.ohos.fasttrpg.MyApplication;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

import java.util.HashMap;
import java.util.Map;

/**
 * PreferenceManager
 *
 * @author liangxu14
 * @date 2022/3/23
 */
public class PreferenceManager {
    public static final String FILE_NAME_TEMPLATE = "preference_file_%s";
    private static Map<String, Preferences> instanceMap = new HashMap<>();

    /**
     * 获取Preferences实例，不存在则创建
     * @param instanceKey
     * @return
     */
    public static Preferences getInstance(String instanceKey) {
        Preferences instance = instanceMap.get(instanceKey);
        if (instance == null) {
            DatabaseHelper databaseHelper = new DatabaseHelper(MyApplication.getMyContext());
            String fileName = String.format(FILE_NAME_TEMPLATE, instanceKey);
            instance = databaseHelper.getPreferences(fileName);
            instanceMap.put(instanceKey, instance);
        }
        return instance;
    }

    /**
     * 移除Preferences实例
     * @param instanceKey
     */
    public static void deleteInstance(String instanceKey) {
        DatabaseHelper databaseHelper = new DatabaseHelper(MyApplication.getMyContext());
        String fileName = String.format(FILE_NAME_TEMPLATE, instanceKey);
        databaseHelper.deletePreferences(fileName);
        instanceMap.remove(instanceKey);
    }
}
